package lock;

import java.sql.Time;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @AUTHOR LYF
 * @DATE 2022/3/18
 * @VERSION 1.0
 * @DESC
 */
public class ReentrantLockDemo {
   static ReentrantLock reentrantLock = new ReentrantLock();
   static Condition condition1  = reentrantLock.newCondition();
   static Condition condition2  = reentrantLock.newCondition();
   static Condition condition3  = reentrantLock.newCondition();

    static class Task1 implements Runnable{
        @Override
        public void run() {
            try {
                //reentrantLock.unlock();
                reentrantLock.lock();
                condition1.await();

                System.out.println("Task1工作！！");
                TimeUnit.SECONDS.sleep(2);
                System.out.println("Task1工作完毕---通知Task2工作");

//                reentrantLock.lock();
                condition2.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                reentrantLock.unlock();
            }
        }
    }

    static class Task2 implements Runnable{
        @Override
        public void run() {
            try {
                //reentrantLock.unlock();
                reentrantLock.lock();
                condition2.await();

                System.out.println("Task2工作！！");
                TimeUnit.SECONDS.sleep(2);
                System.out.println("Task2工作完毕---通知Task3工作");

               // reentrantLock.lock();
                condition3.signalAll();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                reentrantLock.unlock();
            }
        }
    }


    static class Task3 implements Runnable{
        @Override
        public void run() {
            try {
                //reentrantLock.unlock();
                reentrantLock.lock();

                condition3.await();

                System.out.println("Task3工作！！");
                TimeUnit.SECONDS.sleep(2);
                System.out.println("Task3工作完毕--全部工作完毕");
                //condition3.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                reentrantLock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //reentrantLock.unlock();
        new Thread(new Task1()).start();
        new Thread(new Task2()).start();
        new Thread(new Task3()).start();
        System.out.println("各个工人准备就绪");
        TimeUnit.SECONDS.sleep(1);
        condition1.signalAll();
        System.out.println("通知干活！！");

    }
}
